package com.shadow.ui.recycler;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.io.Serializable;
import java.util.LinkedHashMap;

/**
 * @author zhangyu
 * @date 2017/10/31
 */

public class MultipleItemEntity implements MultiItemEntity,Serializable {

    private final SerializableReferenceQueue<LinkedHashMap<Object, Object>> mItemQueue =
            new SerializableReferenceQueue<>();
    private final LinkedHashMap<Object, Object> mMultiFields = new LinkedHashMap<>();
    private final SerializableReference<LinkedHashMap<Object, Object>> mFieldsReference =
            new SerializableReference<>(mMultiFields, mItemQueue);


    public static class MultipleItemEntityBuilder {
        private  final LinkedHashMap<Object, Object> FIELDS = new LinkedHashMap<>();

        public MultipleItemEntityBuilder() {
            FIELDS.clear();
        }

        public final MultipleItemEntityBuilder setItemType(int itemType) {
            FIELDS.put(MultipleField.ITEM_TYPE, itemType);
            return this;
        }

        public final MultipleItemEntityBuilder setField(Object key, Object value) {
            FIELDS.put(key, value);
            return this;
        }

        public final MultipleItemEntityBuilder setFields(LinkedHashMap<Object, Object> fields) {
            FIELDS.putAll(fields);
            return this;
        }

        public MultipleItemEntity build() {
            return new MultipleItemEntity(FIELDS);
        }
    }

    public MultipleItemEntity(LinkedHashMap<Object, Object> fields) {
        mFieldsReference.get().putAll(fields);
    }

    public static MultipleItemEntityBuilder builder(){
        return new MultipleItemEntityBuilder();
    }

    @Override
    public int getItemType() {
        return (int) mFieldsReference.get().get(MultipleField.ITEM_TYPE);
    }

    @SuppressWarnings("unchecked")
    public final <T> T getField(Object key) {
        return (T) mFieldsReference.get().get(key);
    }

    public LinkedHashMap<?, ?> getFields() {
        return mFieldsReference.get();
    }

    public final MultipleItemEntity setField(Object key, Object value) {
        mFieldsReference.get().put(key, value);
        return this;
    }
    public String getJsonData(){
        return JSON.toJSONString(mMultiFields);
    }
}
